/**
 * 会话管理服务
 * 实现对话管理模块设计方案中的API接口
 */

export interface SessionResponse {
  id: string
  title: string
  role_id?: string
  model_config?: {
    model: string
    temperature: number
    max_tokens: number
  }
  settings?: {
    searchEnabled: boolean
    contextThreshold: number
    autoSummary: boolean
  }
  is_favorite?: boolean
  is_archived?: boolean
  message_count?: number
  last_message_at?: string
  created_at: string
  updated_at: string
}

export interface SessionsListResponse {
  sessions: SessionResponse[]
  pagination: {
    page: number
    pageSize: number
    total: number
    totalPages: number
  }
}

export interface SessionCreateRequest {
  title?: string
  role_id?: string
  model?: string
  searchEnabled?: boolean
}

export interface SessionUpdateRequest {
  title?: string
  role_id?: string
  model_config?: {
    model: string
    temperature: number
    max_tokens: number
  }
  settings?: {
    searchEnabled?: boolean
    contextThreshold?: number
    autoSummary?: boolean
  }
  is_favorite?: boolean
  is_archived?: boolean
}

export interface SessionFilters {
  query?: string
  page?: number
  pageSize?: number
  sort?: 'lastActiveAt' | 'title' | 'created_at'
  order?: 'asc' | 'desc'
  filter?: 'favorite' | 'archived' | ''
}

class SessionService {
  private baseURL = '/api/sessions'

  async getSessions(filters: SessionFilters = {}): Promise<SessionsListResponse> {
    const params = new URLSearchParams()
    
    if (filters.query) params.append('query', filters.query)
    if (filters.page) params.append('page', filters.page.toString())
    if (filters.pageSize) params.append('pageSize', filters.pageSize.toString())
    if (filters.sort) params.append('sort', filters.sort)
    if (filters.order) params.append('order', filters.order)
    if (filters.filter) params.append('filter', filters.filter)

    const response = await fetch(`${this.baseURL}?${params}`)
    if (!response.ok) {
      throw new Error(`Failed to fetch sessions: ${response.statusText}`)
    }

    const data = await response.json()
    return data.data
  }

  async createSession(sessionData: SessionCreateRequest): Promise<SessionResponse> {
    const response = await fetch(this.baseURL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(sessionData),
    })

    if (!response.ok) {
      throw new Error(`Failed to create session: ${response.statusText}`)
    }

    const data = await response.json()
    return data.data
  }

  async getSession(sessionId: string): Promise<SessionResponse> {
    const response = await fetch(`${this.baseURL}/${sessionId}`)
    if (!response.ok) {
      throw new Error(`Failed to fetch session: ${response.statusText}`)
    }

    const data = await response.json()
    return data.data
  }

  async updateSession(
    sessionId: string, 
    updates: SessionUpdateRequest
  ): Promise<SessionResponse> {
    const response = await fetch(`${this.baseURL}/${sessionId}`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(updates),
    })

    if (!response.ok) {
      throw new Error(`Failed to update session: ${response.statusText}`)
    }

    const data = await response.json()
    return data.data
  }

  async deleteSession(sessionId: string): Promise<void> {
    const response = await fetch(`${this.baseURL}/${sessionId}`, {
      method: 'DELETE',
    })

    if (!response.ok) {
      throw new Error(`Failed to delete session: ${response.statusText}`)
    }
  }

  async toggleFavorite(sessionId: string): Promise<SessionResponse> {
    const response = await fetch(`${this.baseURL}/${sessionId}/favorite`, {
      method: 'PATCH',
    })

    if (!response.ok) {
      throw new Error(`Failed to toggle favorite: ${response.statusText}`)
    }

    const data = await response.json()
    return data.data
  }

  async toggleArchive(sessionId: string): Promise<SessionResponse> {
    const response = await fetch(`${this.baseURL}/${sessionId}/archive`, {
      method: 'PATCH',
    })

    if (!response.ok) {
      throw new Error(`Failed to toggle archive: ${response.statusText}`)
    }

    const data = await response.json()
    return data.data
  }

  async restoreSession(sessionId: string): Promise<SessionResponse> {
    const response = await fetch(`${this.baseURL}/${sessionId}/restore`, {
      method: 'POST',
    })

    if (!response.ok) {
      throw new Error(`Failed to restore session: ${response.statusText}`)
    }

    const data = await response.json()
    return data.data
  }

  // 批量操作
  async batchToggleFavorite(sessionIds: string[]): Promise<void> {
    await Promise.all(sessionIds.map(id => this.toggleFavorite(id)))
  }

  async batchToggleArchive(sessionIds: string[]): Promise<void> {
    await Promise.all(sessionIds.map(id => this.toggleArchive(id)))
  }

  async batchDelete(sessionIds: string[]): Promise<void> {
    await Promise.all(sessionIds.map(id => this.deleteSession(id)))
  }
}

export const sessionService = new SessionService()